package com.dkd.day20250630;

import java.io.*;
import java.nio.file.*;
import java.util.zip.*;

public class FolderZipper {
    public static void main(String[] args) {
        String baseDir = "D:\\BaiduNetdiskDownload\\讲义 (3)\\讲义"; // 替换为你的讲义文件夹路径

        for (int i = 1; i <= 15; i++) {
            String dayFolderName = String.format("day%02d", i);//day01
            String dayFolderPath = Paths.get(baseDir, dayFolderName).toString();

            // 检查文件夹是否存在
            if (!Files.exists(Paths.get(dayFolderPath))) {
                System.out.println("文件夹不存在: " + dayFolderPath);
                continue;
            }

            String zipFileName = dayFolderName + ".zip";
            String zipFilePath = Paths.get(baseDir, zipFileName).toString();

            try {
                zipFolder(dayFolderPath, zipFilePath);
                System.out.println("成功创建zip文件: " + zipFilePath);
            } catch (IOException e) {
                System.err.println("创建zip文件失败: " + zipFilePath);
                e.printStackTrace();
            }
        }
    }

    private static void zipFolder(String sourceFolderPath, String zipFilePath) throws IOException {
        Path sourcePath = Paths.get(sourceFolderPath);

        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos)) {

            // 获取day文件夹的父路径
            Path parentPath = sourcePath.getParent();

            // 遍历day文件夹中的所有文件和子目录
            Files.walk(sourcePath)
                    .forEach(path -> {
                        try {
                            // 计算相对于day文件夹父目录的路径
                            Path relativePath = parentPath != null ?
                                    parentPath.relativize(path) :
                                    path.getFileName();

                            // 在Windows上替换反斜杠为正斜杠
                            String relativePathStr = relativePath.toString().replace('\\', '/');

                            if (Files.isDirectory(path)) {
                                // 如果是目录，添加一个以/结尾的条目
                                if (!relativePathStr.endsWith("/")) {
                                    relativePathStr += "/";
                                }
                                zos.putNextEntry(new ZipEntry(relativePathStr));
                                zos.closeEntry();
                            } else {
                                // 如果是文件，添加文件内容
                                zos.putNextEntry(new ZipEntry(relativePathStr));
                                Files.copy(path, zos);
                                zos.closeEntry();
                            }
                        } catch (IOException e) {
                            throw new RuntimeException("添加文件到zip失败: " + path, e);
                        }
                    });
        }
    }
}